package com.ikun.admin.websocket.config;


import com.ikun.admin.websocket.constant.WebSocketConstant;
import com.ikun.common.constant.RedisConstant;
import com.ikun.common.manager.RedisManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

/**
 * @ClassName WebSocketConfig
 * @Description:
 * @CreateDate: 2024/9/6 16:42
 */
@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig extends ServerEndpointConfig.Configurator {


    private static RedisManager redisManager;


    public static void init(ApplicationContext applicationContext) {
        redisManager = applicationContext.getBean(RedisManager.class);
    }

    /**
     * 配置websocket容器
     *
     * @return
     */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(WebSocketConstant.MAX_TEXT_SIZE);//设置最大文本消息大小
        container.setMaxBinaryMessageBufferSize(WebSocketConstant.MAX_BINARY_SIZE);//设置最大二进制消息大小
        container.setMaxSessionIdleTimeout(WebSocketConstant.MAX_SESSION_FREE_TIME);//设置最大会话空闲时间
        return container;
    }


    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        log.info("websocket握手");
        String queryString = request.getQueryString();
        if(queryString == null){
            return;
        }
        Long userId = Long.valueOf(queryString.split("=")[1]);
        sec.getUserProperties().put(WebSocketConstant.ONLINE_USER_KEY, userId);
    }


}
